#!/usr/bin/env python
# encoding: utf-8
# waf script for builduing project
# author: Anton Feldmann 
# Copyright 2014 anton.feldmann@gmail.com


import os, sys
from waflib import Build, TaskGen
from waflib.Options import options
from waflib.Configure import conf

name = 'hostfileconfig'

def options(opt):
    opt.add_option('--avahi service path', 
                   action='store',
                   dest='avahi_service',
                   default='/etc/avahi/services/',
                   help='the path to the avahi services [Default: "/etc/avahi/services/"]')

@conf
def find_service(self):
    self.start_msg('start checking for distcc service description')
    node = self.root.find_node('services')
    _path = node and node.abspath() or '' or self.env.AVAHI_SERVICES
 
    self.end_msg('stop checking for distcc service description')

    return self.find_file('hostfileconfig.service', _path);

@conf
def write_service_to_file(self, service):
    try:
        fo = open(os.path.join(conf.env.AVAHI_SERVICES,'hostfileconfig.service') ,"w")
        
        fo.write('<?xml version="1.0" standalone=\'no\'?>\n<!DOCTYPE service-group SYSTEM "avahi-service.dtd">\n<service-group>\n<name replace-wildcards="yes">hostfile on %h</name>\n<service>\n<type>_hostfile._udp</type>\n</service>\n</service-group>')
            
        fo.close()
    except IOError as (errno, strerror):
        print "I/O Error({0}): {1}".format(errno, strerror)
    except:
        print "Unexpected error:", sys.exc_info()[0]

def configure(conf):
    if os.name == 'nt':
        conf.fatal('can not run with Windows')

    conf.env.AVAHI_SERVICES = conf.options.avahi_service

    conf.load(['avahi-browser','hostfile'], tooldir='./waf_tools')

    if not conf.find_service():
        conf.write_service_to_file()

    conf.find_program('grep')
    conf.find_program('egrep')
    conf.find_program('cut')
    conf.find_program('paste')
    

def build(bld):
    if not os.path.isfile('~/.hostfile'):
        bld(rule='touch ~/.hostfile')

    bld(rule='avahi-browse _hostfile._udp -t -r | grep address | egrep -v : | cut -d [ -f 2 | cut -d ] -f 1 | paste -s -d\' \' > ~/.hostsfile')
